package com.android.lovely.ui.activity

import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.android.lovely.R
import com.android.lovely.databinding.ActivityTransactionBinding
import com.android.lovely.ext.fullScreen
import com.android.lovely.framework.BaseActivity
import com.android.lovely.ui.dialog.TransTimeDialog
import com.android.lovely.ui.dialog.TransTypeDialog
import com.android.lovely.ui.fragment.TransListFragment
import com.android.lovely.ui.viewmodel.TransViewModel
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable
import kotlinx.coroutines.flow.collectLatest

/**
 *
 * @author why
 * @date 2025/3/13 16:42
 */
class TansListActivity : BaseActivity<ActivityTransactionBinding>() {

    val viewModel by viewModels<TransViewModel>()
    override fun initView(savedInstanceState: Bundle?) {
        fullScreen()
        mBinding.titleBar.setTitle(getString(R.string.tans_detail))
        mBinding.titleBar.addStatusBarMarginTop()
        "${viewModel.year}-${viewModel.month.padStart(2, '0')}".also {
            mBinding.tvCalendar.text = it
        }
        mBinding.tvType.setText(viewModel.type?.contentResId ?: R.string.all)
        mBinding.tvType.clickable {
            TransTypeDialog().show(supportFragmentManager)
        }
        mBinding.tvCalendar.clickable {
            TransTimeDialog().show(supportFragmentManager)
        }
        initFragment()
        lifecycleScope.launchSafety {
            viewModel.update.collectLatest {
                "${viewModel.year}-${
                    viewModel.month.padStart(
                        2,
                        '0'
                    )
                }".also { mBinding.tvCalendar.text = it }
                mBinding.tvType.setText(viewModel.type?.contentResId ?: R.string.all)
            }
        }
    }

    private fun initFragment() {
        // 创建一个 Fragment 实例
        val fragment = TransListFragment()
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        fragmentTransaction.add(mBinding.flContainer.id, fragment)
        fragmentTransaction.commitNowAllowingStateLoss()
    }
}